package ar.com.photo_admin.domain

import grails.converters.JSON
import java.security.MessageDigest

import grails.plugins.springsecurity.Secured

@Secured(["isAuthenticated()"])
class EventAlbumTokenController {

	def eventAlbumService
	
	def eventService
	
	def springSecurityService
	
	def eventAlbumTokenService
	
	def customMailService
		
	final PROCESS_TOKEN_OK = "PROCESS_TOKEN_OK"
	
	final PROCESS_TOKEN_FAILED = "PROCESS_TOKEN_FAILED"
		
	@Secured(['ROLE_PHOTOGRAPHER', 'ROLE_ADMIN', 'ROLE_CLIENT'])
	def index() {
		redirect(action: "create", params: params)
	}
	
	@Secured(['ROLE_PHOTOGRAPHER', 'ROLE_ADMIN', 'ROLE_CLIENT'])
	def create() {
		User user = springSecurityService.currentUser
		
		List events = Event.allEvents(user).list(sort: "id")
				
		Map eventsMap = [:]
		Event event = null
		
		if (events) {
			def eventId = params.id
			
			event = eventId ? events.find { it.id.toString() == eventId } : events.first()
			events.each { eventsMap.put(it.name, it.id) }			
			
			// If someone hard-code event id..
			if (event == null)
				return redirect(action: "create")			
		}
			
		[event: event, eventsMap: eventsMap as JSON]
	}
	
	@Secured(['ROLE_PHOTOGRAPHER', 'ROLE_ADMIN', 'ROLE_CLIENT'])
	def generateToken() {
		User user = springSecurityService.currentUser
		
		/*
		 * At least one selected album.
		 */
		if (!params.selectedAlbumsIds) {
			render(contentType: "text/json") {
				[ 'error': message(code: 'share.select.at.least.one') ]
			}
			return
		}
		
		List selectedAlbumIds =  (params.selectedAlbumsIds).split(",") as List
				
		/*
		 * Checks if user owns the event.
		 */
		def eventId = params.eventId
		Event event = Event.get(eventId)
		
		if (event && user.isOwner(event)) {
			Set selectedAlbums = EventAlbum.getAll(selectedAlbumIds)
			
			/*
			 * Checks if albums belong to the event
			 */
			if (event.albums?.containsAll(selectedAlbums)) {
				
				String token = eventAlbumTokenService.generateToken(event, selectedAlbums)
								
				EventAlbumToken eventAlbumToken = new EventAlbumToken(token: token, albums: selectedAlbums)
				eventAlbumToken.save(flush:true)
								
				render(template: "generateToken", model: [token: token])
			}
		}
	}
		
	def processToken() {
		def tokenId = params.tokenId
		def status = PROCESS_TOKEN_OK
		def eventId
				
		EventAlbumToken eventAlbumToken = EventAlbumToken.findByToken(tokenId)
		
		if (eventAlbumToken) {
			
			User user = springSecurityService.currentUser
			
			Set eventAlbumTokenAlbums = eventAlbumToken.albums
			
			Set userAlbumsIds = eventAlbumService.getAlbums().collect { it.id }
			Set eventAlbumTokenAlbumsIds = eventAlbumTokenAlbums.collect { it.id }
						
			eventAlbumTokenAlbumsIds.removeAll(userAlbumsIds)
			
			eventAlbumTokenAlbums.each { album ->
				UserAlbumAccess.link(user, album)				
			}
			
			EventAlbum eventAlbum = eventAlbumTokenAlbums.toList().first()
			eventId = eventAlbum.event.id

			Integer albumSize = eventAlbumTokenAlbumsIds.size()
			
			if (eventAlbumTokenAlbumsIds.isEmpty())
				flash.warning = message(code: 'share.albums.noNewAlbumns')
			else
				flash.message = message(code: 'share.albums.success', args: [eventAlbumTokenAlbumsIds.size()])
				
			flash.tokenError = ""
		}
		else {
			flash.tokenError = message(code: 'share.albumsPassword.invalid')
			status = PROCESS_TOKEN_FAILED
		}
		
		if (springSecurityService.isAjax(request)) {
			render(template: "/common/addToken", model: [processTokenStatus: status, eventId: eventId])
		}
		else if (status == PROCESS_TOKEN_OK) {
			redirect(controller: 'event', action: 'show', id: eventId)
		} else
			redirect(controller: 'index', action: 'addEvents')
	}
	
	@Secured(['ROLE_PHOTOGRAPHER', 'ROLE_ADMIN', 'ROLE_CLIENT'])
	def sendEmail() {
		
		def token = params.token
		def tokenUrl = params.tokenUrl
		
		EventAlbumToken eventAlbumToken = EventAlbumToken.findByToken(token)
		Event event = eventAlbumToken.albums.find().event
		User user = springSecurityService.currentUser
		
		def returnMessage = null
		def error = false
		
		if (customMailService.sendShareEventInfo(token, tokenUrl, user, event))
			returnMessage = message(code: 'share.send.mail.success', args: [user.email])
		else {
			returnMessage = message(code: 'share.send.mail.fail', args: [user.email])
			error = true
		}
		
		render(contentType: "text/json") {
			[ 'message': returnMessage, 'error': error ]
		}
	}
}
